from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from goods.models import shangpin, GoodsCategory, Guige, CartInfos, OrderInfos

import time
from django.shortcuts import render, redirect
from goods.pay import get_pay


# Create your views here.

@login_required()  # 用户未登录时，转向登录界面
def index(request):
    # 获取所有商品对象和商品分类对象
    shangpin1 = shangpin.objects.all()
    leibie = GoodsCategory.objects.all()
    return render(request, 'index.html', {'shangpin': shangpin1, 'leibie': leibie})


@login_required()
def leixing(request, id):
    # 根据传入的id值过滤出对应的商品，并获取所有商品分类对象
    goods = shangpin.objects.filter(category_id=id)
    leibie = GoodsCategory.objects.all()
    return render(request, 'index.html', {'shangpin': goods, 'leibie': leibie})


@login_required()  # 用户未登录时，转向登录界面
def detail(request, id):
    # 根据传入的id值过滤出对应的商品，并获取相关的规格对象
    shangpin1 = shangpin.objects.filter(id=id).first()
    guige = Guige.objects.filter(guige_leixing_id=shangpin1.guige_leixing_id)
    return render(request, 'detail.html', {'shangpin': shangpin1, 'guiges': guige})


@login_required()
def showcart(request):
    # 从请求的cookie中获取用户ID
    userid = request.COOKIES.get("userid")
    # 根据用户ID过滤出购物车对象列表
    carts = CartInfos.objects.filter(user_id=userid)  # queryset
    shangpins = []
    for cart in carts:
        # 根据购物车中的商品ID获取对应的商品对象
        shangpin1 = shangpin.objects.get(id=cart.shangpin_id)
        shangpins.append(shangpin1)
    carts_list = list(carts)
    # 将购物车对象和商品对象进行合并
    sumlist = zip(carts_list, shangpins)
    return render(request, 'cart.html', {'sumlist': sumlist})


@login_required()  # 用户未登录时，转向登录界面
def addcart(request, id):
    # 加入购物车
    quantity = request.POST.get('quantity')
    userid = request.COOKIES.get('userid')
    add1 = CartInfos(num=quantity, user_id=userid, shangpin_id=id)
    add1.save()
    # 可以返回购物车页面，也可返回详情页
    shangpin1 = shangpin.objects.filter(id=id).first()
    guige = Guige.objects.filter(guige_leixing_id=shangpin1.guige_leixing_id)
    # 控制页面转向
    return render(request, 'detail.html', {'shangpin': shangpin1, 'guiges': guige})


@login_required()  # 用户未登录时，转向登录界面
def delt(request, id):
    # 从请求的cookie中获取用户ID
    userid = request.COOKIES.get("userid")
    # 根据购物车项的ID删除对应的购物车对象
    CartInfos.objects.filter(id=id).delete()
    carts = CartInfos.objects.filter(user_id=userid)  # queryset
    shangpins = []
    for cart in carts:
        # 根据购物车中的商品ID获取对应的商品对象
        shangpin1 = shangpin.objects.get(id=cart.shangpin_id)
        shangpins.append(shangpin1)
    carts_list = list(carts)
    # 将购物车对象和商品对象进行合并
    sumlist = zip(carts_list, shangpins)
    return render(request, 'cart.html', {'sumlist': sumlist})


# 查看订单中心
def showorderinfo(request):
    # 获取所有订单信息对象
    orderInfos = OrderInfos.objects.all()
    return render(request, 'orderinfo.html', {'orderInfos': orderInfos})


def paysView(request):
    # 从请求中获取订单总价
    total = request.POST.get('total')
    if total:
        # 将订单总价转换为浮点数类型
        total = float(str(total).replace('￥', ''))
        # 生成订单号
        out_trade_no = str(int(time.time()))
        # 构建支付信息字典
        payInfo = dict(price=total, user_id=request.user.id, state='已支付')
        # 将支付信息和支付时间存储到session中
        request.session['payInfo'] = payInfo
        request.session['payTime'] = out_trade_no
        # 构建返回URL
        return_url = 'http://' + request.get_host() + '/goods/orderinfo'
        # 调用get_pay函数获取支付链接
        url = get_pay(out_trade_no, total, return_url)
        print(url)
        # 重定向到支付链接
        return redirect(url)
    else:
        # 如果没有订单总价，重定向到购物车页面
        return redirect('goods:carts')


# 将订单信息写入数据库并显示至页面
@login_required()
def shopperView(request):
    # 从session中获取支付信息和支付时间
    payInfo = request.session['payInfo']
    t = request.GET.get('t', '')
    payTime = request.session.get('payTime', '')
    if t and payTime and t == payTime:
        # 如果支付时间和参数中的t相等，表示支付成功
        payInfo = request.session.get('payInfo', '')
        # 在订单中心中创建订单记录
        OrderInfos.objects.create(**payInfo)
        # 删除session中的支付时间和支付信息
        del request.session['payTime']
        del request.session['payInfo']
    # 根据当前用户查询用户订单信息
    orderInfos = OrderInfos.objects.filter(user_id=request.user.id)
    return render(request, 'orderinfo.html', locals())
